package demo;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class AccessPersonConstructors2 {
    public static void main(String[] args) {
        try {
            Class  clz=Class.forName("demo.Person");
            Object obj=clz.newInstance();//new新建 Instance实例
            System.out.println(obj);

            //获取Person的午餐构造
            Constructor c1 =clz.getDeclaredConstructor();
            obj=c1.newInstance();
            System.out.println(obj);

            //获取Person的单参
            Constructor c2=clz.getDeclaredConstructor(String.class);
            //Person的单参构造为private，这里已超出访问范围
            //通过setAccessable方法
            c2.setAccessible(true);
            obj=c2.newInstance("New Person");
            System.out.println(obj);

            //获取三个参数的构造方法
            Constructor c3=clz.getDeclaredConstructor(String.class,String.class,String.class);

            c3.setAccessible(true);
            obj=c3.newInstance("New Person","beijing","Hello!");
            System.out.println(obj);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}
